package com.example.admin.testdemo.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;

import com.example.admin.testdemo.R;
import com.example.admin.testdemo.adapter.MonitorListAdapter;
import com.example.admin.testdemo.dao.TempData;
import com.example.admin.testdemo.rs232.Command;
import com.example.admin.testdemo.rs232.Serial;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class GzGOldActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private static String TAG = "GzGOldActivity";
    private GridView gv;
    private Serial serial;
    private MonitorListAdapter adapter;
    private int delay = 3;
    private int sendFlag = 0;
    private int recivceFlag = 0;
    private EditText et_cs;
    private EditText et_hds;
    private EditText et_send;
    private EditText et_recive;
    private EditText et_monitor;
    private EditText et_address;
    private Button btn_save;
    private Button btn_hand;
    private EditText et_hand;
    private EditText et_yy;
    private EditText et_result;
    private int x = 1;
    boolean btnSave = false;
    private boolean isSave = false;
    private boolean isHand = false;
    private boolean isSingleDegug = false;
    private ScheduledExecutorService scheduledThreadPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gz_gold);
        initView();
        initData();

    }



    private Serial.DataCallback callback = new Serial.DataCallback() {
        @Override
        public void onDataReceived(byte[] buffer, int size) {
//            Log.e(TAG, "接收：" + Command.printByteInfo(buffer));
            singleDebug(buffer);
            handhandshae(buffer);
            handMonitor(buffer);
        }
    };


    private void singleDebug(byte[] buffer) {
        if (isSingleDegug && buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF4 && buffer[4] == (byte) 0x4B) {
            isSingleDegug = false;
            setEt(et_result, "电子锁正常");
            setEt(et_yy, "正常");
        }
    }


    private void handMonitor(byte[] buffer) {
        if(isSave &&  buffer[0] == (byte) 0xAA && buffer[2] == (byte) 0xF4 && buffer[4] == (byte) 0x4B){
            recivceFlag++;
            setEt(et_recive,recivceFlag);
        }

    }

    private void handhandshae(byte[] buffer) {
        if (isHand) {
            setEt(et_hand, Command.printChar(buffer));
            isHand = false;
        }
    }




    private void initData() {
        serial = Serial.getSerialInstance();
        serial.setCallback(callback);
        startTimer();

    }
    private void startTimer() {
        if (scheduledThreadPool == null) {
            scheduledThreadPool = new ScheduledThreadPoolExecutor(1);
        }
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (isSave) {
                    loopTest();

                }


            }
        }, 0, delay, TimeUnit.SECONDS);

    }

    private void checkMoniterResult(){
        serial.sendData(Command.engineResult(1));
    }


    private void loopCheck() {
        if (serial != null) {
            serial.sendData(Command.outGoodsResult());
        }
    }

    int flag = 1;

    private void loopTest() {
        int layer = Integer.parseInt(et_cs.getText().toString());
        int hd = Integer.parseInt(et_hds.getText().toString());
        int r = getLayer(flag, hd);
        sendCommand(2, x, r);
        setEt(et_monitor, x + "-" + r);
        if (r == hd) {
            x++;
            if (x > layer) {
                x = 1;
            }
        }
        if (flag > 65535) {
            flag = 0;
        }
        flag++;
    }

    private int getLayer(int flag, int hd) {
        int temp = flag % hd;
        if (temp == 0) {
            temp = hd;
        }
        return temp;
    }


    private void initView() {
        gv = findViewById(R.id.gv);
        gv.setOnItemClickListener(this);
        adapter = new MonitorListAdapter(GzGOldActivity.this, TempData.getMonitors(10, 4));
        gv.setAdapter(adapter);
        btn_save = findViewById(R.id.btn_save);
        btn_save.setOnClickListener(this);
        btn_hand = findViewById(R.id.btn_hand);
        btn_hand.setOnClickListener(this);
        et_cs = findViewById(R.id.et_cs);
        et_hds = findViewById(R.id.et_hds);
        et_recive = findViewById(R.id.et_recive);
        et_send = findViewById(R.id.et_send);
        et_monitor = findViewById(R.id.et_monitor);
        et_hand = findViewById(R.id.tv_hand);
        et_address = findViewById(R.id.et_address);
        et_result = findViewById(R.id.et_result);
        et_yy = findViewById(R.id.et_yy);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String temp = adapter.getItem(position);
        String[] tt = temp.split("-");
        isSingleDegug = true;
        setEt(et_result, "");
        setEt(et_result, "电子锁异常");
        setEt(et_yy, "异常");
        sendCommand(2, Integer.parseInt(tt[0]), Integer.parseInt(tt[1]));
    }

    private void sendCommand(int add, int x, int y) {
        if (serial != null) {
            if(x>6){
                x=x+10;
            }
            byte[] command = Command.outGoods(add, x, y);
            serial.sendData(command);
            if (isSave) {
                sendFlag++;
                setEt(et_send, sendFlag);
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_save:
                clicktest();
                break;
            case R.id.btn_hand:
                hands();
                break;
        }
    }



    private void hands() {
        isHand = true;
        et_hand.setText("");
        isSave = false;
        btn_save.setText("开始");
        int add = getEtNum(et_address);
        if (serial != null) {
            serial.sendData(Command.handshake(add));
        }

    }

    private void engineResult() {
        if (serial != null) {
            serial.sendData(Command.engineResult(1));
        }

    }

    private void clicktest() {
        if (btnSave) {
            btn_save.setText("测试中");
            initEt();
            x = 1;
            recivceFlag = 0;
            sendFlag = 0;
            flag = 1;
            btnSave = false;
            isSave = true;
        } else {
            btn_save.setText("开始");
            btnSave = true;
            isSave = false;
        }
    }

    private void initEt() {
        et_recive.setText("0");
        et_send.setText("0");
    }


    private void setEt(final EditText et, final int flag) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et.setText(Integer.toString(flag));
            }
        });
    }

    private void setEt(final EditText et, final String flag) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et.setText(flag);
            }
        });
    }

    private void setBtn(final Button et, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et.setText(msg);
            }
        });
    }

    private int getEtNum(EditText et) {
        int tt = 1;
        String temp = et.getText().toString();
        if (!TextUtils.isEmpty(temp)) {
            tt = Integer.parseInt(temp);
        }
        return tt;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    private void stopTimer() {
        if (scheduledThreadPool != null) {
            scheduledThreadPool.shutdown();
        }
    }
}
